package com.citywithincity.redis.models;

import java.util.List;
import java.util.Set;

import com.citywithincity.db.Page;
import com.citywithincity.interfaces.IDestroyable;
import com.citywithincity.redis.utils.RedisUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

/**
 * 我的收藏
 * @author renxueliang
 *
 */
public class RedisZSetColModel<T> implements IDestroyable {
	private RedisObjectModel<T> objectModel;
	
	private String zsetKey;
	
	public RedisZSetColModel(RedisObjectModel<T> model,String zsetKey) {
		objectModel = model;
		this.zsetKey = zsetKey;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
	protected String getKey(Object userId){
		return new StringBuilder(zsetKey).append(':').append(userId).toString();
	}

	
	public void edit(Pipeline jedis,Object userId, Object id, double score  ){
		jedis.zadd(getKey(userId), score, String.valueOf(id));
	}
	
	public void edit(Object userId, Object id, double score  ){
		
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			jedis.zadd(getKey(userId), score, String.valueOf(id));
			
		}finally{
			if(jedis!=null)jedis.close();
		}
	}
	
	public void delete(Object userId,Object id){
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			jedis.zrem(getKey(userId), String.valueOf(id));
		}finally{
			if(jedis!=null)jedis.close();
		}
		
	}
	
	public void delete(Pipeline jedis,Object userId,Object id){
		jedis.zrem(getKey(userId), String.valueOf(id));
	}
	
	public boolean contains(Object userId,Object id){
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			return jedis.zscore(getKey(userId), String.valueOf(id))!=null;
		}finally{
			if(jedis!=null)jedis.close();
		}
	}
	
	public List<T> getList(Object userId){
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			Set<String> set = jedis.zrange(getKey(userId),0, -1);
			return objectModel.getList(jedis, set);
		}finally{
			if(jedis!=null)jedis.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public Page<T> getPosition(Object userId,int position,int pageSize){
		Jedis jedis = null;
		try{
			jedis = RedisUtil.read();
			String key = getKey(userId);
			int count = (int)(long)jedis.zcard(key);
			if(count==0){
				return Page.EMPTY_PAGE;
			}
			Page<T> result = new Page<T>();
			//最大下表为count-1
			int maxIndex = position + pageSize;
			if(maxIndex > count){
				maxIndex = count;
			}
			Set<String> set = jedis.zrange(key,position, maxIndex-1);
			int page = position / pageSize + 1;
			int total;
			if(count%pageSize==0){
				total = count / pageSize;
			}else{
				total = count / pageSize + 1;
			}
			List<T> list = objectModel.getList(jedis,set);
			result.setPage(page);
			result.setPageSize(pageSize);
			result.setTotalPages(total);
			result.setTotalRows(count);
			result.setList(list);
			return result;
		}finally{
			if(jedis!=null)jedis.close();
		}
	}

	
}
